import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useConfigStore } from '@/store/config'

const routes: RouteRecordRaw[] = [
  {
    name: 'index',
    path: '/index',
    component: () => import('@/views/index/index.vue'),
  },
  {
    name: 'login',
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      noLogin: true
    },
  },
  {
    path: '/',
    redirect: '/index',
  }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

router.beforeEach(async (to, _, next) => {
  console.log(to)
  // 不需要守卫的路由
  if (to.meta.noLogin) {
    next();
    return;
  }
  // 获取用户信息
  const configStore = useConfigStore();
  if (configStore.currentUser) {
    next();
    return;
  } else {
    // 尝试获取用户信息
    const msg = window.$message.info('正在获取用户信息。。。', { duration: 0 })
    try {
      await configStore.getCurrentUser();
      next();
    } catch(err) {
      window.$message.warning(`获取用户信息失败！正在跳转到登录页面。。。`);
      next({ path: '/login' })
    } finally {
      msg.destroy()
    }
  }
})

export default router
